from BloodSpiderAPI import models

from django import forms

from BloodSpiderModel.DjangoResponseTool import response_dict

from BloodSpiderAPI.apis.user.utils import utils_model_to_dict

import time


class UserForm(forms.ModelForm):
    class Meta:
        model = models.User
        fields = ['username', 'password', 'role']


# 创建用户
def create_user(request):
    if request.method == 'POST':
        try:
            form = UserForm(request.POST)
            if form.is_valid():
                # 注册用户的时候需要判断提供注册的用户是否是管理员
                user = form.save()
                user_data = utils_model_to_dict(user)
                return response_dict.response_dict(message="用户创建成功", data=user_data)
            else:
                err = response_dict.get_first_error(form)
                return response_dict.response_dict(message=err, code=1)
        except Exception as e:
            return response_dict.response_dict(data=str(e), code=1, message="创建用户失败")


# 登录
def login(request):
    time.sleep(1)
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = models.User.objects.filter(username=username, password=password).first()
            if user:
                return response_dict.response_dict(message="登录成功", data=utils_model_to_dict(user))
            else:
                return response_dict.response_dict( message="用户名或密码错误", code=1)
      
        except Exception as e:
            return response_dict.response_dict(message=str(e), code=1)


# 设置管理员权限
def set_role(request):  
    if request.method == 'POST':
        try:
            user_id = request.POST.get('user_id') 
            role = int(request.POST.get('role'))
            user = models.User.objects.filter(user_id=user_id).first()
            if user:
                user.role = role
                user.save()
                return response_dict.response_dict(message="权限设置成功")
            else:
                return response_dict.response_dict(message="用户不存在", code=1)
        except Exception as e:
            return response_dict.response_dict(message=str(e), code=1)


# 获取用户信息
def get_user_info(request):
    try:
        return response_dict.response_dict(message="获取用户信息成功", data=utils_model_to_dict(request.user))
    except Exception as e:
        return response_dict.response_dict(message=str(e), code=1)

# 搜索用户
def search_user(request):
    if request.method == 'POST':
        try:
            keyword = request.POST.get('keyword')
            users = models.User.objects.filter(username__contains=keyword)
            user_data = [utils_model_to_dict(user) for user in users]
            return response_dict.response_dict(message="搜索用户成功", data=user_data)
        except Exception as e:
            return response_dict.response_dict(message=str(e), code=1)
    return response_dict.response_dict(message="请求方法错误", code=1)